const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

async function myfetch(options){
  let token=wx.getStorageSync('token')
  let obj={
    url:options.url,
      method:options.method || 'GET',
      dataType:options.dataType || 'json',
      header:{
        'authorization':token
      }
  }
  if(options.data){
    obj.data=options.data
  }
  if(options.header){
    for(let k in options.header){
      obj.header[k]=options.header[k]
    }
  }
  let r=await new Promise((rv,rj)=>{
    obj.success=res=>{
      if(res.statusCode===200){
        rv({ok:true,data:res.data})
      }else{
        rv({ok:false,status:res.statusCode,data:res.data})
      }
    }
    obj.fail=err=>{
      rv({ok:false,status:0,data:err.message})
    }
    if(options.isUpload){
      obj.name=options.name
      obj.filePath=options.filePath
      if(obj.method=='GET') obj.method='POST'
      wx.uploadFile(obj)
    }else{
      wx.request(obj)
    }

    wx.request(obj)
  })
  return r
}


module.exports = {
  formatTime,
  myfetch
}
